//
//  ShowDesiginViewController.m
//  lvtu
//
//  Created by Apple on 12-4-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ShowDesiginViewController.h"
#import "DataSource.h"
#import "NSObject+SBJSON.h"
#import "wxAppDelegate.h"

@implementation ShowDesiginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"展示旅途";
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"旅途展示"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    tempLabel = nil;
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* backbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    backbutton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    [backbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [backbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [backbutton addTarget:self action:@selector(backButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbutton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    [backButtonItem release];
    
    backgroundScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    backgroundScrollView.backgroundColor = [UIColor clearColor];
    backgroundScrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height+200);
    backgroundScrollView.pagingEnabled = NO;
//    backgroundScrollView.scrollEnabled = NO;
    backgroundScrollView.clipsToBounds = YES;
    backgroundScrollView.scrollsToTop = YES;
    backgroundScrollView.showsVerticalScrollIndicator = NO;
    backgroundScrollView.showsHorizontalScrollIndicator = NO;
    backgroundScrollView.delegate = self;
    [self.view addSubview:backgroundScrollView];
    
    profileImageView = [[EGOImageView alloc] initWithFrame:CGRectMake(35, 15, 50, 50)];
    [profileImageView setImage:[UIImage imageNamed:@"bg_user_default.png"]];
    NSString* imageName = [DataSource shareInstance].userInfo.image_filename;
    [profileImageView setImageURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.wxlvtu.com/img.php?filename=%@",imageName]]];
    [backgroundScrollView addSubview:profileImageView];
    
    nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 20, 100, 20)];
    nameLabel.text = [NSString stringWithFormat:@"作者:%@",[DataSource shareInstance].userInfo.name];
    nameLabel.font = [UIFont systemFontOfSize:12];
    nameLabel.backgroundColor = [UIColor clearColor];
    nameLabel.textColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    [backgroundScrollView addSubview:nameLabel];
    [nameLabel release];
    
    timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(95, 40, 100, 20)];
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    timeLabel.text = [NSString stringWithFormat:@"时间:%@",[dateFormatter stringFromDate:today]];
    timeLabel.font = [UIFont systemFontOfSize:12];
    timeLabel.backgroundColor = [UIColor clearColor];
    timeLabel.textColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    [backgroundScrollView addSubview:timeLabel];
    [timeLabel release];
    [dateFormatter release];
    
    UILabel* coverLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 75, 100, 20)];
    coverLabel.text = @"设置封面 :";
    coverLabel.font = [UIFont systemFontOfSize:12];
    coverLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:coverLabel];
    [coverLabel release];
    
    _newHeadPic = [[UIImageView alloc] initWithFrame:CGRectMake(35, 95, 250, 50)];
    [_newHeadPic setImage:[UIImage imageNamed:@"bg_trip_default.png"]];
    [backgroundScrollView addSubview:_newHeadPic];
    
    UIControl* temp = [[UIControl alloc] initWithFrame:_newHeadPic.frame];
    [temp addTarget:self action:@selector(snapPicButtonPress) forControlEvents:UIControlEventTouchUpInside];
    [backgroundScrollView addSubview:temp];
    [temp release];
    
    UILabel* tripLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 150, 100, 20)];
    tripLabel.text = @"点击上传图片";
    tripLabel.font = [UIFont systemFontOfSize:10];
    tripLabel.textColor = [UIColor grayColor]; 
    tripLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:tripLabel];
    [tripLabel release];
    
    UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 170, 100, 20)];
    titleLabel.text = @"设置标题:";
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:titleLabel];
    [titleLabel release];
    
    UIImage* TextFieldImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_imput.png" ofType:nil]];
    nameTextField = [[UITextField alloc] init];
    [nameTextField setFrame:CGRectMake(35, 190, 250, 40)];
    [nameTextField setBackground:TextFieldImage];
    nameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [nameTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [nameTextField setReturnKeyType:UIReturnKeyDone];
    [nameTextField setFont:[UIFont boldSystemFontOfSize:12]];
    [nameTextField setDelegate:self];
    [nameTextField setTextColor:[UIColor grayColor]];
    [nameTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [nameTextField setClipsToBounds:YES];
    [backgroundScrollView addSubview:nameTextField];
    [nameTextField release];
    
    UILabel* detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 240, 100, 20)];
    detailLabel.text = @"备注:";
    detailLabel.font = [UIFont systemFontOfSize:12];
    detailLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:detailLabel];
    [detailLabel release];
    
    UIImage* detailTextFieldImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_imput.png" ofType:nil]];
    UIImage* stretchImg = [detailTextFieldImage stretchableImageWithLeftCapWidth:30 topCapHeight:20];
    detailTestField = [[UITextField alloc] init];
    [detailTestField setFrame:CGRectMake(35, 260, 250, 50)];
    [detailTestField setBackground:stretchImg];
    [detailTestField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [detailTestField setReturnKeyType:UIReturnKeyDone];
    [detailTestField setFont:[UIFont boldSystemFontOfSize:12]];
    [detailTestField setDelegate:self];
    [detailTestField setTextColor:[UIColor grayColor]];
    [detailTestField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [detailTestField setClipsToBounds:YES];
    [backgroundScrollView addSubview:detailTestField];
    [detailTestField release];
    
    //创建注册botton
    UIButton* buttonSignUp = [UIButton buttonWithType:UIButtonTypeCustom];
	buttonSignUp.frame = CGRectMake(80, 320, 160, 40);
    [buttonSignUp setBackgroundImage:[UIImage imageNamed:@"btn_done_normal.png"] forState:UIControlStateNormal];
    [buttonSignUp setBackgroundImage:[UIImage imageNamed:@"btn_done_press.png"] forState:UIControlStateHighlighted];
	[buttonSignUp setTitle:@"发布" forState:UIControlStateNormal];
    buttonSignUp.titleLabel.font = [UIFont boldSystemFontOfSize:16];
	[buttonSignUp addTarget:self action:@selector(signUpButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroundScrollView addSubview:buttonSignUp];
    
    isPicSelect = NO;
}

- (void)viewDidUnload
{
    if (baseAlert) {
        [baseAlert release];
    }
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)backButtonPress:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)signUpButtonPressed:(id)sender
{
    NSString* Path;
    NSDictionary* info;
    NSMutableString* jsons = [[DataSource shareInstance] newTripJSONString];
    if (isPicSelect) {
        Path = [NSString stringWithFormat:@"%@/%@",[[DataSource shareInstance] file_getAppCachePath],@"tripCover.jpg"];
        info = [[NSDictionary alloc] initWithObjectsAndKeys:[DataSource shareInstance].creatTripInfo.starttime,@"start_time",[DataSource shareInstance].creatTripInfo.endtime,@"end_time",@"1",@"c_from_city_id",nameTextField.text,@"name",Path,@"cover_image",jsons,@"json_data",detailTestField.text,@"detail",nil];
    }
    else {
        info = [[NSDictionary alloc] initWithObjectsAndKeys:[DataSource shareInstance].creatTripInfo.starttime,@"start_time",[DataSource shareInstance].creatTripInfo.endtime,@"end_time",@"1",@"c_from_city_id",nameTextField.text,@"name",jsons,@"json_data",detailTestField.text,@"detail",nil];
    }
    baseAlert = [[UIAlertView alloc] initWithTitle:@"正在发布..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [baseAlert show];
    
    UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    aiv.center = CGPointMake(baseAlert.bounds.size.width/2.0f, baseAlert.bounds.size.height-40.0f);
    [aiv startAnimating];
    [baseAlert addSubview:aiv];
    [aiv release];
    
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = CREATTRIP;
    msg.ui_delegate = self; 
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=do_create_line_new" postInfo:info userInfo:msg];
}
#pragma 
#pragma mark   user  action
- (void) snapPicButtonPress
{
    UIActionSheet *menu  = nil;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        menu = [[UIActionSheet alloc]
                initWithTitle: nil
                delegate:self
                cancelButtonTitle:@"取消"
                destructiveButtonTitle:nil
                otherButtonTitles:@"从相册中选", @"拍照", nil];
    }
    else
    {
        menu = [[UIActionSheet alloc]
                initWithTitle: nil
                delegate:self
                cancelButtonTitle:@"取消"
                destructiveButtonTitle:nil
                otherButtonTitles:@"从相册中选", nil];
    }
    
    [menu showInView:self.view];
    [menu release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    printf("User Pressed Button %d\n", buttonIndex + 1);
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        if(buttonIndex == 0)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0 
            
            [self presentModalViewController:ipc animated:YES];	
        }
        else if(buttonIndex == 1)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeCamera;
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0
            ipc.showsCameraControls = YES;
            [self presentModalViewController:ipc animated:YES];	
        }
    }
    else
    {
        if(buttonIndex == 0)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0
            ipc.tabBarItem.title = @"12312312312";
            
            [self presentModalViewController:ipc animated:YES];	
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	UIImage* image = (UIImage*)[info objectForKey:@"UIImagePickerControllerEditedImage"];
	[self dismissModalViewControllerAnimated:YES];
	[picker release];
    _newHeadPic.image = image;
    
    NSString* Path = [NSString stringWithFormat:@"%@/%@",[[DataSource shareInstance] file_getAppCachePath],@"tripCover.jpg"];
    [UIImageJPEGRepresentation(image, 0.4f) writeToFile:Path atomically:YES];
    isPicSelect = YES;
}

#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [backgroundScrollView setContentOffset:CGPointMake(0, 140) animated:YES];   
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [nameTextField resignFirstResponder];
    [backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES]; 
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    
    if ([string isEqualToString:@"\n"])
    {//按下return键
        //这里隐藏键盘，不做任何处理
        [textField resignFirstResponder];
        //        [self willLoginWeibo];
        return NO;
    }
    else
    {
        return YES;
    }
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
        [nameTextField setText:@""];
        [nameTextField setPlaceholder:@""];
        [nameTextField setTextColor:[UIColor grayColor]];

    return YES;
}

#pragma -mark DataSourceDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
//    if (coreMsg.data == CREATTRIP) {
//        NSString* travelId = (NSString*)data;
////        NSString* jsonString = [NSString stringWithFormat:@"{\"2012-03-04\":{\"0\":{\"c_city_id\":1,\"0\":[{\"c_shop_id\":\"1_1_2822\"},{\"c_shop_id\":\"1_1_2822\"}],\"1\":[{\"c_shop_id\":\"1_1_2822\"}]},\"2\":{\"c_city_id\":1,\"2\":[{\"c_shop_id\":\"1_1_2822\"}]}},\"2012-03-05\":{\"0\":{\"c_city_id\":4,\"0\":[{\"c_shop_id\":\"1_1_2822\"}]}}}"];
//        NSMutableString* jsons = [[DataSource shareInstance] JSONString:[DataSource shareInstance].designtripInfo];
////        NSString* json = [[DataSource shareInstance].designtripInfo JSONRepresentation];
//        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:travelId,@"c_travel_line_id",jsons,@"json_data",nil];
//        CoreMsg* msg = [[CoreMsg alloc] init];
//        msg.data = CREATEVENTLIST;
//        msg.ui_delegate = self; 
//        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=do_create_event_list" postInfo:info userInfo:msg];
//    }
//    else
    if ((coreMsg.data = CREATTRIP))
    {
        [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发布成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
//        [self.navigationController popViewControllerAnimated:YES];
        [[wxAppDelegate getAppDelegate] enterMytripView];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    NSString* message;
    if ([data isKindOfClass:[NSString class]]) {
        if ([data isEqualToString:@"name"]) {
            message = @"旅途名字不能为空";
        }
        else if ([data isEqualToString:@"end_time"]){
            message = @"没有旅途内容哟";
        }
        else {
            message = data;
        }
    }
    else {
        message = data;
    }
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alert.tag = 2001;
    [alert show];
    [alert release];
}

@end
